<template>
    <div>
        <div class="table-wrap">
            <el-row class="pt20">
                <el-form ref="form" :model="form" label-width="80px" class="demo-form-inline">
                    <el-row>
                        <el-col :span="2">
                            <pers-button type="primary" @click="add()" perms="kanke:education:gradeclass:add-teacher"
                                label="添加老师">添加老师</pers-button>
                        </el-col>
                        <el-col :span="2"
                            v-if="isShow(['kanke:education:gradeclass:teacher-batch-remove', 'kanke:education:gradeclass:teacher-batch-change'])">
                            <el-form-item label="">
                                <el-select v-model="form.operType" placeholder="批量操作" clearable filterable>
                                    <el-option label="批量移出" value="1" @click.native="handleClickSelect(1)"
                                        v-if="hasPermission('kanke:education:gradeclass:teacher-batch-remove')"></el-option>
                                    <el-option label="批量换班" value="2" @click.native="handleClickSelect(2)"
                                        v-if="hasPermission('kanke:education:gradeclass:teacher-batch-change')"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="2">
                            <el-input style="width: 220px;margin-left: 251px;" placeholder="请输入老师账号/名称"
                                v-model="form.searchText" clearable>
                                <i slot="suffix" class="el-input__icon el-icon-search"
                                    style="font-size:20px;font-weight: bold;" @click="search"></i>
                            </el-input>
                        </el-col>
                        <el-col :span="18">
                        </el-col>
                    </el-row>
                </el-form>

            </el-row>
            <el-table ref="multipleTable" :data="tableData" :loading="loading" size="mini"
                @selection-change="handleSelectionChange" style="width: 100%;margin-bottom: 20px;" row-key="id" border
                stripe default-expand-all>
                <el-table-column type="selection" width="55">
                </el-table-column>
                <el-table-column prop="realname" label="老师姓名" header-align="center" align="center">
                    <template slot-scope="scope">

                        <el-link type="primary" @click="linkTeacherDetail(scope.row)"
                            v-if="hasPermission('kanke:education:teacher:detail')">
                            {{ scope.row.realname }}
                        </el-link>
                    </template>
                </el-table-column>
                <el-table-column prop="account" label="老师账号" header-align="center" align="center"></el-table-column>
                <el-table-column prop="role_name" label="角色" header-align="center" align="center"></el-table-column>
                <el-table-column prop="status" label="状态" header-align="center" align="center"></el-table-column>
                <el-table-column prop="handle" align="center" fixed="right" width="120" label="操作"
                    v-if="isShow(['kanke:education:gradeclass:teacher-change', 'kanke:education:gradeclass:teacher-remove'])">
                    <template slot-scope="scope">
                        <PersButton type="text" perms="kanke:education:gradeclass:teacher-change" label="换班"
                            @click="handleShift(scope.row)">
                        </PersButton>
                        <PersButton type="text" perms="kanke:education:gradeclass:teacher-remove" label="移出"
                            @click="handleRemove(scope.row)">
                        </PersButton>
                    </template>
                </el-table-column>
            </el-table>
            <div class="block">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="form.pageNumber" :page-sizes="[10, 50, 100, 200]" :page-size="form.pageSize"
                    background layout="total, sizes, prev, pager, next, jumper" :total="form.total">
                </el-pagination>
            </div>
            <ShiftClass v-if="showShift" :visible.sync="showShift" @handleReload="init()" :id="shiftId"
                :userType="userType" :class_id="class_id" />

            <AddTeacher v-if="showAddTeacher" :visible.sync="showAddTeacher" @handleReload="init()" :class_id="class_id"
                :ids="ids" />
        </div>

        <!--弹出层  添加编辑-->
        <el-dialog :visible.sync="openAdd" width="600px" append-to-body :title="!formAdd.id ? '新增员工' : '编辑员工'">
            <el-form ref="form" :model="formAdd" label-width="80px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="员工头像" prop="headimg_url">
                            <el-image class="round-image" :src="formAdd.headimg_url">
                            </el-image>
                            <el-button type="primary" @click="isShowPic = true" size="mini"
                                style="margin-left: 10px;">上传头像</el-button>
                            <select-img :show="isShowPic" @update="cleanDiaglog" :selectType="imgnum" :source="1"
                                @selectSure="selectImgs" :type="0"></select-img>
                        </el-form-item>
                    </el-col>

                    <el-col :span="24">
                        <el-form-item label="*员工账号:" prop="account">
                            <el-input v-model="formAdd.account" placeholder="建议使用老师手机号码作为账号" size="small" clearable
                                :readonly="formAdd.readonly" />
                            <el-link type="info" style="font-size: 12px;">
                                请使用数字1-9字母a-z或A-Z且大于6位小于12位用于登录学校App或管理后台
                            </el-link>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="*员工姓名:" prop="realname">
                            <el-input v-model="formAdd.realname" placeholder="限50字以内" size="small" clearable />
                        </el-form-item>
                    </el-col>

                    <el-col :span="24">
                        <el-form-item label="*角色:" prop="role_name" class="demo-form-inline">
                            <el-select size="mini" v-model="formAdd.role_id" placeholder="请选择" filterable clearable>
                                <el-option v-for="item in formAdd.roleList" :key="item.id" :label="item.role_name"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="员工生日:" prop="realname">
                            <div class="block">
                                <el-date-picker size="mini" v-model="formAdd.birthday" type="date"
                                    value-format="yyyy-MM-dd" placeholder="选择生日">
                                </el-date-picker>
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="所在班级:" prop="class_ids" class="demo-form-inline">
                            <el-select size="mini" v-model="formAdd.class_names" multiple placeholder="请选择" filterable
                                clearable>
                                <el-option collapse-tags="true" v-for="item in classList" :key="item.id"
                                    :label="item.class_name" :value="item.class_name">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="24">
                        <el-form-item label="员工性别:">
                            <el-radio-group v-model="formAdd.gender">
                                <el-radio :label="1">男</el-radio>
                                <el-radio :label="0">女</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="openAdd = false" size="small">取 消</el-button>
                <el-button type="primary" @click="!formAdd.id ? submitFormAdd('formAdd') : subEditFormAdd('formAdd')"
                    size="small">确 定</el-button>
            </div>
        </el-dialog>

    </div>

</template>

<script>
import { hasPermission, isShow } from '@/common/permission';
import { allocate, del, resetPass, edit, getTeacherList } from "@/api/kanke/teacher/teacher";
import { getClassData, teacherRemove, teacherShift, isCanDel } from "@/api/kanke/gradeclass/gradeclass";
import ShiftClass from './ShiftClass';
import AddTeacher from "@/views/kanke/education/gradeclass/components/AddTeacher";
import PersButton from '../../../../../components/PersButton.vue';
let _that;

export default {
    name: 'Teacher',
    components: {
        AddTeacher,
        ShiftClass,
        PersButton
    },
    props: {
        class_id: {
            // type: Number,
            default: 0
        },
        teacher_names: {
            type: Array,
            default: []
        }
    },
    data() {
        return {
            loading: false,
            tableData: [],
            classList: [],
            form: {
                realname: '',
                class_id: this.class_id,
                pageSize: 10,
                pageNumber: 1,
            },
            openAdd: false,
            formAdd: {
                id: '',
                headimg_url: '',
                realname: '',
                account: '',
                role_id: 19,
                gender: 0,
                birthday: '',
                class_ids: [],
                class_names: [],
                readonly: false,
                roleList: [{ 'id': 19, 'role_name': '科目主管' }]
            },
            multipleSelection: [],
            isShowPic: false,
            imgnum: 1,
            showShift: false,
            shiftId: [],// 员工id 
            userType: 1,  //1为教师  2为学生
            //添加老师
            showAddTeacher: false,
            ids: [],
            gotoDel: true
        }
    },
    created() {
        _that = this;
        _that.init(true);
        _that.getClassData();
    },
    methods: {
        hasPermission,
        isShow,
        init() {
            _that.loading = true;
            // console.log('init', _that.form);
            if (!_that.form.class_id) {
                this.$message('参数错误~~');
                return;
            }
            getTeacherList(_that.form).then((res) => {
                console.log(res);
                _that.tableData = res.data.list;
                _that.form.total = res.data.total;
                _that.loading = false;
                this.setIds(res.data.list)
            })
            this.$emit('handleReload');
        },
        setIds: function (arr) {
            this.ids = [];
            if (arr.length > 0) {
                for (let i = 0; i < arr.length; i++) {
                    this.ids.push(parseInt(arr[i].id));
                }
            }
        },
        search: function () {
            _that.loading = true;
            _that.form.pageSize = 10;
            _that.form.pageNumber = 1;
            _that.init();
        },
        handleSizeChange: function (e) {
            _that.form.pageSize = e;
            _that.init();
        },
        handleCurrentChange: function (e) {
            _that.form.pageNumber = e;
            _that.init();
        },
        getClassData() {
            getClassData().then((res) => {
                console.log('classinfo', res);
                _that.classList = res.data.list;
            })
        },
        edit(data) {
            _that.openAdd = true;
            console.log('员工edit', data);
            let intClassids = data.class_ids.map(item => parseInt(item));
            console.log(intClassids);
            //转一下class_ids
            let editForm = {
                id: data.id,
                headimg_url: data.headimg_url,
                realname: data.realname,
                account: data.account,
                readonly: true,
                gender: data.gender,
                birthday: data.birthday,
                class_ids: data.class_ids,
                class_names: data.class_names
            }
            Object.assign(_that.formAdd, editForm);
        },
        add: function () {
            this.showAddTeacher = true;
        },
        handleClickSelect(operType) {
            console.log('teacher muti', this.multipleSelection);
            if (!this.multipleSelection || this.multipleSelection.length == 0) {
                this.$message('请选择需要操作的老师');
                return false;
            }
            if (operType == 1) {
                //批量移出
                this.handleRemove('');
            }
            if (operType == 2) {
                //批量换班
                this.handleShift('');
            }
        },
        async handleRemove(obj) {

            if (obj) {
                this.shiftId = [obj.id];
                console.log('teacher single', this.shiftId);
            } else {
                let arr_multi = this.multipleSelection;
                this.shiftId = [];
                for (let i = 0; i < arr_multi.length; i++) {
                    this.shiftId.push(arr_multi[i].id);
                }
                console.log('teacher multi id', this.multipleSelection);
            }
            if (this.shiftId.length == this.teacher_names.length) {
                //判断是否可以删除
                await isCanDel({ type: 3, teacher_id: this.shiftId[0], class_id: this.class_id }).then((res) => {
                    if (res.code == 200) {
                        if (!res.data) {
                            this.$message({ type: 'error', message: '该班级里有学生,必须得留一个老师' });
                            this.gotoDel = false;
                        }
                    } else {
                        this.$message({ type: 'warning', message: res.msg });
                        this.gotoDel = false;
                    }
                });
                if (!this.gotoDel) {
                    this.gotoDel = true;
                    return
                }
            }

            this.$confirm('此操作会将所选成员移出该组且无法恢复\n' + '\n' + '确定要移出?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {

                teacherRemove({ teacher_ids: this.shiftId, class_id: this.class_id }).then((res) => {
                    console.log('teacher remove return', res);
                    if (res.code == 200) {
                        this.$message({ type: 'success', message: '移出成功!' });
                        _that.init();
                    } else {
                        this.$message({ type: 'warning', message: res.msg });
                    }
                })

            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });

        },
        async handleShift(obj) {
            if (obj) {
                this.shiftId = [obj.id];
                console.log('teacher single', this.shiftId);
            } else {
                let arr_multi = this.multipleSelection;
                this.shiftId = [];
                for (let i = 0; i < arr_multi.length; i++) {
                    this.shiftId.push(arr_multi[i].id);
                }
                console.log('teacher multi id', this.multipleSelection);
            }
            if (this.shiftId.length == this.teacher_names.length) {
                //判断是否可以删除
                await isCanDel({ type: 3, teacher_id: this.shiftId[0], class_id: this.class_id }).then((res) => {
                    if (res.code == 200) {
                        if (!res.data) {
                            this.$message({ type: 'error', message: '该班级里有学生,必须得留一个老师' });
                            this.gotoDel = false;
                        }
                    } else {
                        this.$message({ type: 'warning', message: res.msg });
                        this.gotoDel = false;
                    }
                });
                if (!this.gotoDel) {
                    this.gotoDel = true;
                    return
                }
            }
            this.showShift = true;
        },
        cleanDiaglog() {
            this.isShowPic = false;
        },
        selectImgs(res) {
            this.formAdd.headimg_url = res[0].urls
            this.isShowPic = false;
        },
        submitFormAdd(e) {
            console.log(e);
            edit(this.formAdd).then((res) => {
                // console.log(res)
                if (res.code == 200) {
                    this.msgSuccess(res.msg);
                    this.openAdd = false;
                    this.init();
                } else {
                    this.msgError(res.msg);
                }
            })

        },
        subEditFormAdd: function () {
            edit(_that.formAdd).then((res) => {
                if (res.code == 200) {
                    _that.msgSuccess(res.msg)
                    _that.openAdd = false;
                    _that.init();
                } else {
                    _that.msgError(res.msg);
                }
            })
        },
        linkTeacherDetail: function (data) {
            this.$router.push({ path: 'detail', query: { id: data.id } });
            // this.$router.push({ path: '/kanke/detail', query: { id: data.id } });
        },
        toggleSelection(rows) {
            if (rows) {
                rows.forEach(row => {
                    this.$refs.multipleTable.toggleRowSelection(row);
                });
            } else {
                this.$refs.multipleTable.clearSelection();
            }
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        }
    }
}


</script>

<style lang="scss" scoped>
.demo-form-inline {
    ::v-deep .el-select .el-input {
        width: 300px;
    }
}

.el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
}

.round-image {
    width: 55px;
    /* 或者你想要的大小 */
    height: 45px;
    /* 和宽度相同 */
    border-radius: 50%;
    /* 使得图片变为圆形 */
    overflow: hidden;
    /* 超出容器的图片部分将被隐藏 */
}
</style>